package com.example.musicplayer.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import com.example.musicplayer.R;
import com.example.musicplayer.adapter.MusicItemAdapter;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.musicTools.MusicListType;
import com.example.musicplayer.musicTools.MusicMatchType;
import com.example.musicplayer.musicTools.MusicOp;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.service.MusicTabViewService;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.view.ListenSoftInputView;
import com.example.musicplayer.windowTools.WindowTools;

import java.util.ArrayList;
import java.util.List;

public class MusicSearchActivity extends BaseActivity {
    public static final int RESULT_CODE = 1000;
    public static final String TYPE = "musicListType";
    public static final String MUSIC_MENU = "musicMenu";
    public static final String NEED_LOCATE = "locate";
    public static final String LOCATE_ID = "locateId";
    private List<MusicInfo> mMusicList;
    private MusicItemAdapter mAdapter;
    private ListView mListView;
    private MusicListType mMusicListType;
    private MusicMenu mMusicMenu;
    private String mMatchString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowTools.lightStatusBar(getWindow());
        setEnableMusicTabView(true);
        setContentView(R.layout.activity_music_search);
        setEnableMusicListener(true);
        registerMusicListener(getMusicServiceBinder());
        initView();
        mMusicListType = MusicListType.valueOf(getIntent().getStringExtra(TYPE));
        String menuName = getIntent().getStringExtra(MUSIC_MENU);
        mMusicMenu = MusicInfo.getMusicMenuByName(menuName);
        mMatchString = "";
        //setup music list
        switch (mMusicListType) {
            case TYPE_FAVORITE:
                mMusicList = MusicInfo.getFavoriteMusic();
                break;
            case TYPE_MENU:
                List<Integer> idList = MusicOp.sort(menuName);
                mMusicList = new ArrayList<>();
                if (idList != null) {
                    for (int i = 0; i < idList.size(); i++) {
                        MusicInfo temp = MusicInfo.getMusicInfoById(idList.get(i));
                        if (temp != null) {
                            mMusicList.add(temp);
                        }
                    }
                }
                break;
            case TYPE_LOCAL:
            case TYPE_PURCHASED:
            case TYPE_OTHER:
            default:
                mMusicList = MusicInfo.getLocalMusic();
                break;
        }
        //setup adapter and set listener
        mAdapter = new MusicItemAdapter(this, new ArrayList<MusicInfo>(), getMusicServiceBinder(),
                MusicItemAdapter.MODE_SEARCH);
        mListView.setAdapter(mAdapter);
        View footerView = LayoutInflater.from(this).inflate(R.layout.footer_view, mListView, false);
        mListView.addFooterView(footerView, null, false);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mAdapter.getCount() > 0 && mAdapter.getItem(position) instanceof MusicInfo) {
                    MusicInfo musicInfo = (MusicInfo) mAdapter.getItem(position);
                    MusicService.MusicBinder musicBinder = getMusicServiceBinder();
                    if (musicBinder != null) {
                        if (musicInfo.getId() != musicBinder.getId() || musicBinder.getMusicListType() != mMusicListType) {
                            getMusicServiceBinder().start(mMusicMenu, mAdapter.getMusicList(), musicInfo, mMusicListType);
                        } else if (!musicBinder.isPlaying()) {
                            musicBinder.start();
                        }
                        if (MusicPlayerSettings.isAutoIntoPlayScreen()) {
                            jumpToMusicPlayActivity();
                        }
                    }
                }
            }
        });
        //return and locate music
        mAdapter.setOnLocateMusicListener(musicInfo -> {
            if (musicInfo != null) {
                Intent intent = new Intent();
                intent.putExtra(NEED_LOCATE, true);
                intent.putExtra(LOCATE_ID, musicInfo.getId());
                MusicSearchActivity.this.setResult(RESULT_CODE, intent);
                finishActivity();
            }
        });
        //edit text listener
        ((EditText) findViewById(R.id.edittext)).addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String currentString = s.toString();
                if (currentString.contains(mMatchString) && mMatchString.length() > 0) {
                    mAdapter.setMusicList(MusicOp.match(mAdapter.getMusicList(), currentString, MusicMatchType.MATCH_ALL));
                } else {
                    mAdapter.setMusicList(MusicOp.match(mMusicList, currentString, MusicMatchType.MATCH_ALL));
                }
                mMatchString = currentString;
                findViewById(R.id.clear).setVisibility(mMatchString.length() == 0 ? View.GONE : View.VISIBLE);
                if (mMatchString.length() > 0 && mAdapter.getCount() == 0) {
                    findViewById(R.id.search_fail_area).setVisibility(View.VISIBLE);
                    String text = "没有找到与\"" + mMatchString + "\"相关的结果";
                    ((TextView) findViewById(R.id.search_fail_text)).setText(text);
                } else {
                    findViewById(R.id.search_fail_area).setVisibility(View.GONE);
                }
            }
        });
        findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((EditText) findViewById(R.id.edittext)).setText("");
            }
        });
        //keyboard state listener
        ((ListenSoftInputView) findViewById(R.id.listener)).setOnKeyboardStateChangeListener(new ListenSoftInputView.
                OnKeyboardStateChangeListener() {
            @Override
            public void onKeyboardStateChanged(int state) {
                MusicTabViewService.MusicTabViewBinder binder = getMusicTabViewServiceBinder();
                if (binder != null && isActivityResumed()) {
                    if (state == ListenSoftInputView.OnKeyboardStateChangeListener.STATE_HIDE) {
                        binder.shouldShowView(true);
                    } else if (state == ListenSoftInputView.OnKeyboardStateChangeListener.STATE_SHOW) {
                        binder.shouldShowView(false);
                    }
                }
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            findViewById(R.id.edittext).requestFocus();
        }
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finishActivity();
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //去除toolbar中的标题
            actionBar.setDisplayShowTitleEnabled(false);
        }
        mListView = findViewById(R.id.listview);
    }

    private void finishActivity() {
        finish();
        setPendingTransition(R.anim.normal_right_enter, R.anim.normal_right_exit);
    }

    @Override
    protected void onMusicPrepared(MusicInfo musicInfo) {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onMusicEmpty(MusicInfo musicInfo) {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }
}